package org.nanotek.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.ejb.Stateless;
import javax.persistence.Query;

import org.nanotek.Base;
import org.nanotek.Identifiable;
import org.nanotek.beans.ArtistCredit;
import org.nanotek.beans.Release;
import org.nanotek.dao.ReleaseDAO;

@Stateless
@SuppressWarnings("serial")
public class ReleaseDAOImpl extends LocalBaseDAO<Release> implements
		ReleaseDAO<Release> {

	@Override
	public  Set<Release> findReleases(Set<Base<?>> artistCredits) {
		String jpql = "Select r from Release r inner join r.artistCreditReference a where a.artistCreditId in (:param)";
		Query query = em.createQuery(jpql,Release.class);
		/*long [] values = artistCredits.stream().map(p -> p.getId()).toArray();*/
		List<Long>credits = new ArrayList<Long>();
		for (Base<?> a : artistCredits){
			ArtistCredit credit = (ArtistCredit) a;
			credits.add((Long) credit.getArtistCreditId());
		}
		query.setParameter("param",credits);
		return new HashSet<Release>(query.getResultList());
	}

	@Override
	public  Set<Release> findReleases(String artistCredits) {
		String jpql = "Select r from Release r inner join r.artistCreditReference a where a.artistCreditId in (:param)";
		Query query = em.createQuery(jpql,Release.class);
		/*long [] values = artistCredits.stream().map(p -> p.getId()).toArray();*/
		return new HashSet<Release>(query.getResultList());
	}
	
	@Override
	public List<Release> loadAll() {
		return em.createQuery("from Release",Release.class).getResultList();
	}

	@Override
	public List<Release> listRecords(Integer firstResult, Integer maxResults) {
		return  em.createQuery("from Release",Release.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList();
	}

	@Override
	public  <T extends Serializable> Release find(T id) {
		return (Release) em.find((Class<T>) id,  Release.class);
	}
}
